package com.attendance.utils.aliyun.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.attendance.utils.aliyun.AliyunToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * oss 工具类
 *
 * @author 今朝
 * @date 2021/03/18
 */
@Component
public class AliyunOss {
    @Autowired
    private AliyunToken token;

    public AliyunToken getToken() {
        return token;
    }

    /**
     * 上传字节数组
     *
     * @param ossFile 操作系统文件
     */
    public OssFileResult uploadByteArray(OssFile ossFile) {
        String url = token.getOss().getAddress() + ossFile.getUrl() + ossFile.getFileName();
        OSS ossClient = new OSSClientBuilder().build(token.getOss().getEndpoint(), token.getAccessKeyId(), token.getAccessKeySecret());
        PutObjectRequest putObjectRequest = new PutObjectRequest(token.getOss().getBucketName(), url, new ByteArrayInputStream(ossFile.getFileData()));
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        OssFileResult result = new OssFileResult();
        result.setUrl("https://" + token.getOss().getBucketName() + "." + token.getOss().getEndpoint() + "/" + url);
        return result;
    }

}
